//
//  FinishWithDrawViewController.m
//  DA_V
//
//  Created by 周季阳 on 15/5/9.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "FinishWithDrawViewController.h"
#import "InterFace.h"
#import "UIViewAdditions.h"
#import "BindingViewController.h"
#import "YoungAllData.h"
#import "GMDCircleLoader.h"
#import "Alart_ZhiFuView.h"
#import "AFNetworking.h"
#import "EncryptionData.h"
#import "JSONKit.h"

@interface FinishWithDrawViewController ()<YoungDelegate,UITextFieldDelegate>
{
    Alart_ZhiFuView *_zhiFuAlartView;//提交订单时的弹出框
    UIView *_alertBackview;
}
@property(nonatomic,retain)NSString *isRang;
@end
@implementation FinishWithDrawViewController
@synthesize isRang;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden=YES;
    
    self.view.backgroundColor = [self colorWithHexString:@"#F5F5F5"];
    [self initNav];
    navTitle.text = @"绑定信息";
    
    YoungAllData *data = [[YoungAllData alloc]init];
    data.delegate = self;
    [data checkBank:[[NSUserDefaults standardUserDefaults] objectForKey:@"userID"]];
    [GMDCircleLoader setOnView:self.view withTitle:@"加载中···" animated:YES];

}
#pragma mark - 返回
-(void)clickBackBtn{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark - 加载失败
-(void)requistFail{
    [GMDCircleLoader hideFromView:self.view animated:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 检查银行卡回调
-(void)checkBank:(NSDictionary *)sign{
    NSLog(@"%@",sign);
    [GMDCircleLoader hideFromView:self.view animated:YES];

    [self initUI:[[sign objectForKey:@"data"]objectForKey:@"CardNumber"] andBankBranch:[[sign objectForKey:@"data"]objectForKey:@"BankBranch"] andCardholder:[[sign objectForKey:@"data"]objectForKey:@"CardHolder"] andCertificateNumber:[[sign objectForKey:@"data"]objectForKey:@"CertificateNumber"] andIsAllowedModify:[[sign objectForKey:@"data"]objectForKey:@"IsAllowedModify"] andBankName:[[sign objectForKey:@"data"]objectForKey:@"BankName"]];
}
#pragma mark - initUI   
-(void)initUI:(NSString *)BankCardNumber andBankBranch:(NSString *)BankBranch andCardholder:(NSString *)Cardholder andCertificateNumber:(NSString *)CertificateNumber andIsAllowedModify:(NSString *)IsAllowedModify andBankName:(NSString *)BankName{
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, navView.bottom+20, SCREEN_WIDTH-20, 27)];
    backImage.image = [UIImage imageNamed:@"bangdingyinhangka-xiugaixinxi"];
    [self.view addSubview:backImage];
    
    UILabel *topLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, SCREEN_WIDTH-30, 27)];
    topLabel.text = @"当前绑定账户";
    topLabel.textAlignment = NSTextAlignmentLeft;
    topLabel.font = [UIFont systemFontOfSize:15];
    topLabel.textColor = [UIColor blackColor];
    [backImage addSubview:topLabel];
    
    isRang = [NSString stringWithFormat:@"%@",IsAllowedModify];
    
    //label
    UILabel *label1 = [self createLabel:@"银行卡号:" andFrame:CGRectMake(10, backImage.bottom+5, 98, 25)];
    UILabel *label2 = [self createLabel:@"开户地:" andFrame:CGRectMake(10, label1.bottom+5, 98, 25)];
    UILabel *label3 = [self createLabel:@"开户人姓名:" andFrame:CGRectMake(10, label2.bottom+5, 98, 25)];
    UILabel *label4 = [self createLabel:@"开户身份证号:" andFrame:CGRectMake(10, label3.bottom+5, 98, 25)];
    UILabel *label5 = [self createLabel:@"绑定银行:" andFrame:CGRectMake(10, label4.bottom+5, 98, 25)];
    //value
    UILabel *laabel1 = [self createLabelValue:BankCardNumber andFrame:CGRectMake(label1.right, backImage.bottom+5, SCREEN_WIDTH-label1.right-10, 25)];
    UILabel *laabel2 = [self createLabelValue:BankBranch andFrame:CGRectMake(label1.right, laabel1.bottom+5, SCREEN_WIDTH-label1.right-10, 25)];
    UILabel *laabel3 = [self createLabelValue:Cardholder andFrame:CGRectMake(label1.right, laabel2.bottom+5, SCREEN_WIDTH-label1.right-10, 25)];
    UILabel *laabel4 = [self createLabelValue:CertificateNumber andFrame:CGRectMake(label1.right, laabel3.bottom+5, SCREEN_WIDTH-label1.right-10, 25)];
    UILabel *laabel5 = [self createLabelValue:BankName andFrame:CGRectMake(label1.right, laabel4.bottom+5, SCREEN_WIDTH-label1.right-10, 25)];

    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(10, laabel4.bottom+100, SCREEN_WIDTH-20, 43);
    [btn setBackgroundImage:[UIImage imageNamed:@"bangdingyinhangka-xiugai"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickUpdate) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, btn.bottom+10, SCREEN_WIDTH-20, 60)];
    title.numberOfLines = 0;
    title.text = @"修改银行卡会首先解绑已经绑定的银行卡";
    title.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];
    title.textAlignment = NSTextAlignmentCenter;
    title.textColor = [UIColor redColor];
    [self.view addSubview:title];
    
    
//    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    //[rightBtn setTitle:@"返回" forState:UIControlStateNormal];
//    rightBtn.frame = CGRectMake(0, SCREEN_HEIGHT-0.088*SCREEN_HEIGHT, SCREEN_WIDTH, 0.088*SCREEN_HEIGHT);
//    //rightBtn.titleLabel.font = [UIFont systemFontOfSize:12];
//    //rightBtn.backgroundColor = [UIColor whiteColor];
//    [rightBtn setBackgroundImage:[UIImage imageNamed:@"backBtn"] forState:UIControlStateNormal];
//    [rightBtn addTarget:self action:@selector(clickRightBtn) forControlEvents:UIControlEventTouchUpInside];
//    //[rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [self.view addSubview:rightBtn];

}
#pragma mark - 修改
-(void)clickUpdate{
    if ([isRang isEqualToString:@"1"]) {
        [self careteAlertPassword];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"银行卡已产生交易并正式绑定，如需修改请联系客服" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

#pragma -mark 提交订单时的弹出输入密码提示框
-(void)careteAlertPassword{
    
    UIWindow *windows = [[[UIApplication sharedApplication] delegate] window];
    
    _alertBackview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _alertBackview.backgroundColor = [UIColor blackColor];
    _alertBackview.alpha = 0.4;
    [windows addSubview:_alertBackview];
    
    _zhiFuAlartView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndexedSubscript:12];
    _zhiFuAlartView.frame = CGRectMake(60, SCREEN_HEIGHT/2-90, SCREEN_WIDTH-120, 140);
    _zhiFuAlartView.password.delegate = self;
    [_zhiFuAlartView.affirmBut addTarget:self action:@selector(affirmClick) forControlEvents:UIControlEventTouchUpInside];
    [_zhiFuAlartView.cancelBut addTarget:self action:@selector(cancelButClick) forControlEvents:UIControlEventTouchUpInside];
    [windows addSubview:_zhiFuAlartView];
    
    UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap)];
    [singleTapGestureRecognizer setNumberOfTapsRequired:1];
    [_alertBackview addGestureRecognizer:singleTapGestureRecognizer];
            
    NSString *title = [NSString stringWithFormat:@"请输入您的支付密码"];
    _zhiFuAlartView.titleAlart.text = title;
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    //    NSMutableString *text = [textField.text mutableCopy];
    //    [text replaceCharactersInRange:range withString:string];
    //    return ([text length] >= 6);
    return YES;
}
-(void)singleTap{
    [_zhiFuAlartView.password resignFirstResponder];
}
#pragma -mark 点击弹出框的确定交易
- (void)affirmClick{
    if (_zhiFuAlartView.password.text== nil ||[_zhiFuAlartView.password.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入支付密码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
    [self yanzhengPassword];
}


#pragma mark 验证密码
- (void)yanzhengPassword{
       [GMDCircleLoader setOnView:self.view withTitle:@"验证密码中···" animated:YES];
        YoungAllData *data = [[YoungAllData alloc]init];
        data.delegate = self;
        [data checkTrade:[[NSUserDefaults standardUserDefaults]objectForKey:@"userID"] andTradePass:_zhiFuAlartView.password.text];
}
-(void)xiugai{
    [GMDCircleLoader setOnView:self.view withTitle:@"修改中···" animated:YES];
    NSString *userid = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSMutableDictionary *  smallGoodsDic = [NSMutableDictionary dictionaryWithCapacity:1];
    [smallGoodsDic setObject: userid forKey:@"AgentID"];
    [smallGoodsDic setObject:_zhiFuAlartView.password.text forKey:@"TradePass"];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:smallGoodsDic options:NSJSONWritingPrettyPrinted error:nil];

    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
    NSString *str = [self encodeString:jsonString key:@"hotkeycuk"];

    NSDictionary *paramer = @{@"sign":str};
    NSString *urls = [NSString stringWithFormat:@"http://api.dw521.com/api/profile/bind.php?action=cancel"];
    [manager POST:urls parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"修改银行卡信息responseObject=%@",responseObject);
        EncryptionData *encryption = [[EncryptionData alloc]init];
        NSString * str =[encryption decryption:[responseObject objectForKey:@"sign"] :@"hotkeycuk"];
        NSDictionary *dic = [str objectFromJSONString];
//        [self checktrade:dic];
        
        [GMDCircleLoader hideFromView:self.view animated:YES];
        if ([[dic objectForKey:@"status"] isEqualToString:@"success"]) {
            BindingViewController  *binging = [[BindingViewController alloc]init];
            binging.zName =
            binging.isWhere = @"3";
            [self.navigationController pushViewController:binging animated:YES];
            
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dic objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }



    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
           [GMDCircleLoader hideFromView:self.view animated:YES];
    }];
}
-(NSString *)encodeString:(NSString *)data key:(NSString *)key{
    //    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    //
    //    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",data);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [data length]; i++) {
        position = i % keyLength;
        strChar = [data characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
    
    return base64String1;
}

#pragma -mark 修改回调
-(void)checktrade:(NSDictionary *)sign{
     [GMDCircleLoader hideFromView:self.view animated:YES];
    if ([[sign objectForKey:@"status"] isEqualToString:@"success"]) {
        [self xiugai];
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[sign objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
#pragma -mark 点击弹出框的取消交易
- (void)cancelButClick{
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
}

#pragma mark - 创建label
-(UILabel *)createLabel:(NSString *)title andFrame:(CGRect)frame{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = title;
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment= NSTextAlignmentRight;
    [self.view addSubview:label];
    return label ;
}
-(UILabel *)createLabelValue:(NSString *)title andFrame:(CGRect)frame{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = title;
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment= NSTextAlignmentLeft;
    [self.view addSubview:label];
    return label ;
}
#pragma mark - 返回上一个界面
-(void)clickRightBtn{
    [self.navigationController popToRootViewControllerAnimated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
